package com.qiangesoft.activiti.controller;

import com.qiangesoft.activiti.constant.ProcessConstant;
import com.qiangesoft.activiti.constant.R;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 流程实例 控制器
 *
 * @author qiangesoft
 * @date 2024-02-27
 */
@RestController
@RequestMapping("/instance")
public class ProcessInstanceController {

    @Autowired
    private RuntimeService runtimeService;

    @GetMapping("/start")
    public R start() {
        // 启动流程：提供流程key，业务key，主题
        String businessId = "101";
        ProcessInstance processInstance = runtimeService.createProcessInstanceBuilder()
                .processDefinitionKey(ProcessConstant.PROCESS_KEY)
                .businessKey(ProcessConstant.BUSINESS_KEY_PREFIX + businessId)
                .name("请假流程")
                .start();
        return R.ok(processInstance.toString());
    }

    @GetMapping("/list")
    public R list() {
        // 查询进行中的流程实例
        List<ProcessInstance> processInstanceList = runtimeService.createProcessInstanceQuery()
                .processDefinitionKey(ProcessConstant.PROCESS_KEY)
//                .deploymentId("")
//                .processInstanceId("")
//                .processInstanceBusinessKey("")
//                .processInstanceNameLike("请假流程")
                .active()
                .orderByProcessInstanceId().desc()
                .list();
        return R.ok(processInstanceList.toString());
    }

    @GetMapping("/get")
    public R get(String instanceId) {
        // 某个实例
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(instanceId)
                .singleResult();
        return R.ok(processInstance == null ? null : processInstance.toString());
    }

}
